package com.gombe.credit.app.ui.activity

import android.net.Uri
import android.view.View
import androidx.camera.core.AspectRatio
import androidx.camera.core.CameraSelector
import androidx.camera.core.ImageCapture
import androidx.camera.core.ImageCaptureException
import androidx.camera.core.Preview
import androidx.camera.lifecycle.ProcessCameraProvider
import androidx.core.content.ContextCompat
import com.gombe.credit.app.GombeCreditApp
import com.gombe.credit.app.common.CommonActivity
import com.gombe.credit.app.databinding.ActGombeCreditCameraSelfieBinding
import com.gombe.credit.app.event.GombeCreditEventPointType
import com.gombe.credit.app.request.HttpHelper
import com.gombe.credit.app.request.IHttpCallback
import com.gombe.credit.app.utils.GombeCreditTitleBarUtil
import com.gombe.credit.app.utils.GombeCreditImageLoader
import com.gombe.credit.app.utils.imgcovert.ImageConvert
import com.gombe.credit.app.utils.log.GombeCreditLogger
import com.gombe.credit.lib.adapter.GombeCreditOnSingleClickListener
import org.json.JSONObject
import java.io.File
import java.util.concurrent.ExecutorService
import java.util.concurrent.Executors

/**
 * GombeCredit
 * @Author wwdeng
 * @CreateTime: 2024/11/22 17:12
 * @Annotation：自拍照
 */
class ActGombeCreditCameraSelfie: CommonActivity() {
    lateinit var binding: ActGombeCreditCameraSelfieBinding

    private lateinit var cameraExecutor: ExecutorService
    private var imageCapture: ImageCapture? = null
    private var imgUri: Uri? = null
    private var imgUsePath = ""


    override fun takeGombeCreditRootView(): View {
        binding = ActGombeCreditCameraSelfieBinding.inflate(layoutInflater)
        return binding.root
    }

    override fun initGombeCreditView() {
        GombeCreditTitleBarUtil.setStatusBarLightMode(this, false)
        binding.selfieTitleLayout.setPadding(0, GombeCreditTitleBarUtil.getStatusBarHeight(),0,0)

        cameraExecutor = Executors.newSingleThreadExecutor()
        startCameraSelfie()
    }

    override fun initGombeCreditListener() {
        binding.selfieImgBack.setOnClickListener(object : GombeCreditOnSingleClickListener(){
            override fun onSingleClick(v: View?) {
                finish()
            }
        })
        binding.selfieImgCustomer.setOnClickListener(object : GombeCreditOnSingleClickListener(){
            override fun onSingleClick(v: View?) {
                val eventTitle = "SelfieCamera Page"
                showCustomerDialog(eventTitle)
                addEventPointRequestAction(GombeCreditEventPointType.GOMBECREDIT_TRACK_CLICK.CUSTOMER,eventTitle)
            }
        })
        //拍照
        binding.imgCameraTake.setOnClickListener(object : GombeCreditOnSingleClickListener(){
            override fun onSingleClick(v: View?) {
                addEventPointRequestAction(GombeCreditEventPointType.GOMBECREDIT_TRACK_CLICK.CAMERA_TAKE_PHOTO,"SelfieCamera Page")
                takeCameraSelfieFilePhoto()
            }
        })

        //重拍
        binding.imgCameraRemake.setOnClickListener(object : GombeCreditOnSingleClickListener(){
            override fun onSingleClick(v: View?) {
                addEventPointRequestAction(GombeCreditEventPointType.GOMBECREDIT_TRACK_CLICK.STEP_SELFIE_REMAKE,"SelfieCamera Page")
                showCameraFaceTakeView()
            }
        })

        //使用
        binding.imgCameraUse.setOnClickListener(object : GombeCreditOnSingleClickListener(){
            override fun onSingleClick(v: View?) {
                addEventPointRequestAction(GombeCreditEventPointType.GOMBECREDIT_TRACK_CLICK.STEP_SELFIE_USE_PHOTO, imgUsePath)
                showGombeCreditLoading()
                // 图片处理
                ImageConvert.covert(context = this@ActGombeCreditCameraSelfie, uri = imgUri) { localPath, bitmap ->
                    if (localPath != null){
                        GombeCreditLogger.e("imageConvert success>>>>>>>$localPath")
                        uploadGombeCreditImageAction(localPath)
                    }
                }
            }
        })
    }

    override fun takeGombeCreditData() {
    }

    /**
     * 打开相机预览
     */
    private fun startCameraSelfie() {
        showCameraFaceTakeView()
        val cameraProviderFuture = ProcessCameraProvider.getInstance(this)
        cameraProviderFuture.addListener(Runnable {
            val cameraProvider: ProcessCameraProvider = cameraProviderFuture.get()
            val preview = Preview.Builder()
                .setTargetAspectRatio(AspectRatio.RATIO_16_9)
                .build()
                .also {
                    it.setSurfaceProvider(binding.selfieCameraView.surfaceProvider)
                }
            imageCapture = ImageCapture.Builder().build()
            //打开前置摄像头
            val cameraSelector = CameraSelector.DEFAULT_FRONT_CAMERA
            try {
                cameraProvider.unbindAll()
                cameraProvider.bindToLifecycle(this, cameraSelector, preview,imageCapture)
            } catch(exc: Exception) {
            }
        }, ContextCompat.getMainExecutor(this))
    }

    /**
     * 拍照并保存到本地
     */
    private fun takeCameraSelfieFilePhoto(){
        if (imageCapture != null){
            //创建文件
            val filePath = GombeCreditApp.app.filesDir.absolutePath
            val outputFile = File(filePath,"${System.currentTimeMillis()}.jpg")
            if (!outputFile.exists()){
                outputFile.mkdir()
            }
            //创建输出选项对象
            val metadata = ImageCapture.Metadata().apply {
                // 当为前置摄像头时镜像；前置摄像头预览时默认就是镜像
                isReversedHorizontal = true
            }
            //创建文件
            val outputFileOptions = ImageCapture.OutputFileOptions.Builder(outputFile).setMetadata(metadata).build()
            //开始拍照
            imageCapture?.takePicture(outputFileOptions,ContextCompat.getMainExecutor(this),object : ImageCapture.OnImageSavedCallback{
                override fun onImageSaved(outputFileResults: ImageCapture.OutputFileResults) {
                    imgUri = outputFileResults.savedUri
                    imgUri?.path?.let { path ->
                        GombeCreditLogger.e("take photo complete>>>>>>>${path}")
                        imgUsePath = path
                        GombeCreditImageLoader.instance?.loadImageUrl(this@ActGombeCreditCameraSelfie,binding.selfiePreview,imgUsePath,0)
                        showCameraFaceCompleteView()
                    }
                }
                override fun onError(exception: ImageCaptureException) {
                    GombeCreditLogger.e("take photo failed >>>>>>>${exception.message}")
                }
            })
        }
    }

    /**
     * 显示拍照样式
     */
    private fun showCameraFaceTakeView(){
        binding.selfiePreview.visibility = View.GONE
        binding.imgCameraTake.visibility = View.VISIBLE
        binding.imgCameraUse.visibility = View.GONE
        binding.imgCameraRemake.visibility = View.GONE
    }

    /**
     * 显示拍照完成页面
     */
    private fun showCameraFaceCompleteView(){
        binding.selfiePreview.visibility = View.VISIBLE
        binding.imgCameraTake.visibility = View.GONE
        binding.imgCameraUse.visibility = View.VISIBLE
        binding.imgCameraRemake.visibility = View.VISIBLE
    }

    /**
     * 图片上传完成
     */
    fun showGombeCreditUploadImageSuccess(imgPath: String, imgUrl: String) {
        val intent = intent
        intent.putExtra("imgLocalPath",imgUsePath)
        intent.putExtra("imgUrl",imgUrl)
        setResult(RESULT_OK,intent)
        finish()
    }

    /**
     * 图片上传
     */
    private fun uploadGombeCreditImageAction(imgPath: String){
        HttpHelper.setTag(this)
        HttpHelper.upload(imgPath,object : IHttpCallback {
            override fun onRequestSuccess(data: JSONObject) {
                val obj = data.optJSONObject("obj")
                obj?.let {
                    val imgUrl = it.optString("url")
                    showGombeCreditUploadImageSuccess(imgPath,imgUrl)
                }
            }
            override fun onRequestError(error: JSONObject) {
                showGombeCreditToast(error.optString("errorMsg"))
            }

            override fun onRequestFinish() {
                hideGombeCreditLoading()
            }
        })
    }

    override fun onStart() {
        super.onStart()
        addEventPointRequestAction(GombeCreditEventPointType.GOMBECREDIT_TRACK_PAGE.STEP_SELFIE_CAMERA_START)
    }

    override fun onDestroy() {
        super.onDestroy()
        HttpHelper.cancelTag(this)
        addEventPointRequestAction(GombeCreditEventPointType.GOMBECREDIT_TRACK_PAGE.STEP_SELFIE_CAMERA_END)
        cameraExecutor.shutdown()
    }
}